import {useEffect, useState} from "react";
import {useRequest} from "ahooks";
import {getUserInfoService} from "../service/user";
import {useDispatch} from "react-redux";
import {loginReducer} from "../redux/userReducer";
import useGetUserInfo from "./useGetUserInfo";

function useLoadUserData() {
    const [waitingUser, setWaitingUser] = useState(true);
    const dispatch = useDispatch()
    const {run} = useRequest(getUserInfoService, {
        manual: true,
        onSuccess(result) {
            const {nickname, username} = result
            dispatch(loginReducer({nickname, username}))
        },
        onFinally() {
            setWaitingUser(false)
        }
    })
    const {username} = useGetUserInfo()
    useEffect(() => {
        if (username) {
            setWaitingUser(false)
            return
        }
        run()
    }, [username])
    return {waitingUser}
}

export default useLoadUserData
